<script setup lang="ts">
import type { UploadMethod } from '@/uni_modules/wot-design-uni/components/wd-upload/types'
import ocrService from '@/api/modules/ocr/ocr.ts'
import orderService from '@/api/modules/order/order.ts'
import SafeTopContainer from '@/components/SafeTopContainer/SafeTopContainer.vue'
import { useUcarDict } from '@/hooks/useUcarDict.ts'
import { userAgreementText } from '@/pages/login/agreementText.ts'
import HistoryOrder from '@/pages/orderSearch/historyOrder.vue'
import { useToast } from 'wot-design-uni'

// 字典项
const { product_type } = useUcarDict('product_type')
const tabs = ['下单查询', '历史订单']
const activeIndex = ref(0)
const agreementChecked = ref(false)
const totalPrice = ref(0)

// upload
const uploadList = ref([])

const exampleImgUrl = ref('https://i.mji.rip/2025/07/22/43e7c7f2a39fd618a487c13a94895d06.jpeg')

const agreementShow = ref(false)
const payDetailShow = ref(false)
const uploadUrl = import.meta.env.VITE_APP_BASE_API
const productUuid = ref('')
const productType = ref('')
const productTypeName = ref('')
const toast = useToast()
// 行驶证表单
const drivingLicenseForm = ref({
  brandModel: '',
})

// 新增：用于缓存生成的订单信息
const createdOrder = ref<{ orderUuid: string, orderCode: string, vinNo: string } | null>(null)

function setActive(index: number) {
  if (activeIndex.value !== index) {
    activeIndex.value = index
  }
}

onLoad((res) => {
  if (res?.price) {
    totalPrice.value = res.price
    productUuid.value = res.productUuid
    productType.value = res.productType
    productTypeName.value = res.productTypeName
  }
})

function navigateBack() {
  uni.switchTab({
    url: '/pages/home/index',
  })
}

function navigateToContact() {
  uni.switchTab({
    url: '/pages/my/index',
  })
}

async function navigateToPay() {
  if (!agreementChecked.value) {
    toast.warning('请先阅读并同意用户协议')
    return
  }

  const { brandModel, fileUuid, vinNo } = drivingLicenseForm.value

  // 如果已经有订单，直接走支付逻辑
  if (createdOrder.value) {
    return proceedToPay(createdOrder.value.orderCode, createdOrder.value.orderUuid, createdOrder.value.vinNo)
  }

  const params = {
    brandModel,
    fileUuid,
    vinNo,
    productUuidList: [productUuid.value],
  }

  try {
    const res = await orderService.addOrder(params)
    const { data, code } = res

    if (code !== 200 || !data?.orderCode) {
      toast.error('生成订单失败')
      return
    }

    // toast.success('下单成功')

    // 缓存订单信息
    createdOrder.value = {
      orderCode: data.orderCode,
      orderUuid: data.orderUuid,
      vinNo,
    }

    return proceedToPay(data.orderCode, data.orderUuid, vinNo)
  }
  catch (err) {
    console.error('下单异常:', err)
    const {
      code,
      message,
    } = err
    if (code === 319) {
      toast.warning(message)
    }
    else {
      toast.error('生成订单失败')
    }
  }
}

async function proceedToPay(orderCode: string, orderUuid: string, vinNo?: string) {
  const amount = Number(totalPrice.value)
  try {
    const balancePayData = await payWithBalance(orderCode, amount)
    if (balancePayData?.code === 200) {
      await handlePostPaySuccess(orderUuid)
    }
    else {
      const wechatPayData = await payWithWeChat(orderCode, balancePayData.data.unpaidAmount, 'U车查')
      if (wechatPayData) {
        await handlePostPaySuccess(orderUuid)
      }
    }
  }
  catch (err: any) {
    console.error('支付异常:', err)
    // 判断签名逻辑
    if (err?.code === 314) {
      toast.warning('请先完成签名')
      return uni.navigateTo({
        url: `/pages/my/signature?orderCode=${orderCode}&vinNo=${vinNo}`,
      })
    }
    toast.error('支付失败')
    // 失败后处理订单状态
    // await updateOrderStatus({
    //   orderUuid,
    //   orderStatus: 'waitVaild',
    //   payStatus: 'waitPay',
    // }, '支付失败', `/pages/order/detail?orderUuid=${orderUuid}`, true)
  }
}

async function handlePostPaySuccess(orderUuid: string) {
  await updateOrderStatus({
    orderUuid,
    orderStatus: 'vaild',
    payStatus: 'paid',
  }, '支付成功', `/pages/order/detail?orderUuid=${orderUuid}`)

  createdOrder.value = null
  if (
    productType.value === 'cheXinMengQueryAccident'
    || productType.value === 'lemonQueryAccident'
  ) {
    await orderService.orderUseUcarQueryApi({ orderUuid })
  }
}
// 封装状态更新和跳转逻辑
async function updateOrderStatus(params, msg, redirectUrl, isError = false) {
  try {
    await orderService.updateOrderStatus(params)
    const toastFn = isError ? toast.error : toast.success

    toastFn({
      msg,
      duration: 1000,
      closed: () => {
        uni.reLaunch({ url: redirectUrl })
      },
    })
  }
  catch (err) {
    console.error('订单状态更新失败', err)
  }
}

function handleClickExample() {
  uni.previewImage({
    urls: [exampleImgUrl.value],
  })
}

// 自定义上传
function handleUploadSuccess(res, file, options) {
  const { onSuccess, onError } = options

  try {
    const data = JSON.parse(res.data || '{}')
    if (data.code === 200) {
      toast.success('上传成功')
      onSuccess?.(res, file, data)
      drivingLicenseForm.value = data.data
      const ocrBrandPriceListVoList = data.data?.ocrBrandPriceListVoList
      if (productType.value === 'uCarPreciseQuery' || productType.value === 'uCarQueryMainten') {
        if (ocrBrandPriceListVoList) {
          const findPrice = ocrBrandPriceListVoList.find(item => item.productType === productType.value)
          if (findPrice) {
            totalPrice.value = findPrice.realPrice
          }
          else {
            drivingLicenseForm.value.brandModel = ''
            toast.warning('暂不支持该品牌车型查询')
          }
        }
        else {
          drivingLicenseForm.value.brandModel = ''
          toast.warning('暂不支持该品牌车型查询')
        }
      }
    }
    else {
      const errMsg = data.message || '上传失败'
      toast.error(errMsg)
      onError?.({ ...res, errMsg }, file)
    }
  }
  catch (err) {
    toast.error('返回数据解析失败')
    onError?.({ ...res, errMsg: '数据格式错误' }, file)
  }
}

const handleCustomUpload: UploadMethod = (file, formData, options) => {
  const action = `${uploadUrl}/ucar/ocr/ocrDrivingLicenseRecognition`
  const { onSuccess, onError } = options
  const token = getToken()
  const uploadTask = uni.uploadFile({
    url: action, // 替换成你自己的上传接口地址
    filePath: file.url,
    header: {
      Authorization: token,
    },
    name: 'file',
    success: (res) => {
      handleUploadSuccess(res, file, options)
    },
    fail: (err) => {
      toast.error('上传失败')
      onError?.(err, file)
    },
  })
  uploadTask.onProgressUpdate((res) => {
    options.onProgress(res, file)
  })
}

function handleConfirmVinNo(e) {
  const vinRegex = /^[A-HJ-NPR-Z0-9]{17}$/
  const vinNo = e.value
  if (!vinRegex.test(vinNo)) {
    drivingLicenseForm.value.vinNo = ''
    drivingLicenseForm.value.brandModel = ''
    return toast.warning('车架号格式错误')
  }
  console.log(vinNo)
  ocrService.vinIdentifyVehicle({
    vin: vinNo,
  }).then((res) => {
    console.log(res)
    const data = res.data
    drivingLicenseForm.value.vinNo = data.vin
    drivingLicenseForm.value.brandModel = data.brandName
    const ocrBrandPriceListVoList = data?.ocrBrandPriceListVoList
    if (ocrBrandPriceListVoList) {
      const findPrice = ocrBrandPriceListVoList.find(item => item.productType === productType.value)
      if (findPrice) {
        totalPrice.value = findPrice.realPrice
      }
      else {
        drivingLicenseForm.value.brandModel = ''
        toast.warning('暂不支持该品牌车型查询')
      }
    }
    else {
      drivingLicenseForm.value.brandModel = ''
      toast.warning('暂不支持该品牌车型查询')
    }
  })
}

function handleOcrClose() {
  drivingLicenseForm.value.fileUuid = null
  drivingLicenseForm.value.brandModel = ''
  drivingLicenseForm.value.vinNo = ''
  uploadList.value = []
}
</script>

<template>
  <safe-top-container :padding-bottom="15" :fixed="true" :show-bg-color="true" bg-color="#FFF" :show-placeholder="true">
    <wd-navbar left-arrow custom-class="!bg-transparent" :title="`u车查-${productTypeName}`" :bordered="false" @click-left="navigateBack" />
  </safe-top-container>
  <div class="order-search-container mb-10 bg-gray-100 p-3 pt-6">
    <div class="tabs">
      <div class="tabs-fillet-corner">
        <div
          v-for="(tab, index) in tabs"
          :key="index"
          class="tabs-fillet-corner-item-wrap"
        >
          <div
            class="tabs-fillet-corner-item"
            :class="index === activeIndex ? 'tabs-fillet-corner-item-active' : 'flex items-center justify-center'"
            @click="setActive(index)"
          >
            <div class="tabs-fillet-corner-item-text harmony-text">
              {{ tab }}
            </div>
            <div v-if="index === activeIndex " class="flex items-center justify-center">
              <div class="tabs-fillet-corner-item-icon iconfont icon-joy-smile" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="bg-white">
      <div v-if="activeIndex === 0" class="mb-27 rounded-lg p-5">
        <div class="upload-container">
          <div class="mb-1 text-center text-lg text-[#333333FF] font-bold">
            请上传行驶证
          </div>
          <div class="mb-3 text-center text-base text-[#666666FF]">
            请确保证件边框完整、字体清晰、亮度均匀
          </div>
          <wd-upload
            :file-list="uploadList"
            :limit="1"
            :upload-method="handleCustomUpload"
            accept="image"
            class="card-upload"
            @remove="handleOcrClose"
          >
            <div class="upload-box h-50 flex flex-col cursor-pointer items-center justify-center rounded-lg space-y-4">
              <div class="relative inline-block">
                <div class="upload-icon h-15 w-15 flex items-center justify-center rounded-full bg-[#5066F6]">
                  <img src="@/static/svg/upload-camera.svg" alt="upload" class="h-6 w-6">
                </div>
              </div>
              <p class="text-[#333333FF] font-bold">
                点击上传行驶证
              </p>
            </div>
          </wd-upload>
        </div>
        <div class="input-container mt-5">
          <wd-cell title="车架号:" vertical size="large">
            <wd-input v-model="drivingLicenseForm.vinNo" type="text" placeholder="请输入车架号" confirm-type="done" @blur="handleConfirmVinNo" :disabled="drivingLicenseForm.fileUuid"/>
          </wd-cell>
          <wd-cell title="品牌:" vertical size="large">
            <wd-input v-model="drivingLicenseForm.brandModel" type="text" placeholder="输入车架号或者上传行驶证自动识别" disabled />
          </wd-cell>
          <wd-cell vertical size="large" title="查询须知:">
            <!--            <div class="text-orange-500 font-medium"> -->
            <!--              示例：报告样式 -->
            <!--            </div> -->
            <!--            <div -->
            <!--              class="mt-3 h-10 w-full flex items-center justify-center border-1px border-[#364EF3] rounded border-dotted bg-[#F0F2FF] p-3 text-[18px] text-[#2540F3]" -->
            <!--              @click="handleClickExample" -->
            <!--            > -->
            <!--              点击预览 -->
            <!--            </div> -->
            <div class="cursor-pointer text-orange-500 decoration-underline" @click="handleClickExample">
              示例：报告样式
            </div>
          </wd-cell>
          <wd-cell vertical size="large" title="联系方式:">
            <div class="cursor-pointer text-[#364EF3] decoration-underline" @click="navigateToContact">
              我的-联系客服
            </div>
          </wd-cell>
        </div>
        <div class="rounded-lg bg-orange-50 p-2 text-sm text-orange-800 space-y-1">
          <div class="flex items-start gap-2">
            <wd-icon name="warn-bold" size="20px" />
            <div class="text-red-500 font-medium">
              免责申明:
            </div>
          </div>
          <p class="text-xs leading-relaxed">
            此报告的信息依赖第三方平台采集车辆信息的准确性、及时性和完整性，故本平台不保证信息的真实性、准确性和完整性。因此报告仅供试用者进行车辆检测或交易时的重要参考之一。
          </p>
        </div>
      </div>
      <history-order v-if="activeIndex === 1" :product-uuid="productUuid" />
    </div>
  </div>
  <div v-if="activeIndex === 0" class="payment-container fixed bottom-0 w-full border-t bg-white pb-5 pt-3">
    <div class="px-4">
      <div class="mb-3">
        <div class="flex items-center">
          <wd-checkbox v-model="agreementChecked" custom-class="relative" />
          <span class="text-sm">已阅读并同意<wd-text type="primary" text="《用户协议》" @click="agreementShow = true" /></span>
        </div>
        <!--        <div class="flex items-center"> -->
        <!--          <wd-checkbox v-model="signatureChecked" custom-class="relative" /> -->
        <!--          <span class="text-sm">我确认是<wd-text type="primary" text="是车主本人或经过车主授权" @click="agreementShow = true" />使用该服务</span> -->
        <!--        </div> -->
      </div>
      <div class="flex items-center">
        <div class="flex-1">
          <div class="flex items-baseline">
            <!--            <span class="text-sm text-[#333333FF]">合计:</span> -->
            <span class="text-2xl text-red-500 font-semibold tracking-normal">
              ￥{{ totalPrice }}
            </span>
            <span class="ml-3 text-sm text-orange-500" @click="payDetailShow = true">
              明细
            </span>
          </div>
        </div>
        <wd-button type="primary" custom-class="w-[30%] !text-base" :disabled="totalPrice === 0 || drivingLicenseForm.brandModel === ''" @click="navigateToPay">
          去支付
        </wd-button>
      </div>
    </div>
  </div>
  <wd-action-sheet v-model="agreementShow" title="用户协议" custom-class="custom-action-sheet" custom-header-class="custom-action-sheet__header" @close="agreementShow = false">
    <div class="h-[50vh] overflow-y-auto whitespace-pre-line px-5 text-sm">
      {{ userAgreementText }}
    </div>
  </wd-action-sheet>
  <wd-action-sheet v-model="payDetailShow" title="支付明细" custom-header-class="custom-action-sheet__header" @close="payDetailShow = false">
    <div class="p-2">
      <div class="rounded-lg bg-[#F5F5F5] p-5">
        <div class="text-[18px] text-[#282D30]">
          {{ productTypeName }}
        </div>
        <div class="mt-3 flex items-center justify-between">
          <div class="text-[#666]">
            {{ formatTime(new Date(), 'YYYY-MM-DD') }}
          </div>
          <div class="text-orange-500">
            ￥ {{ totalPrice }}
          </div>
        </div>
      </div>
    </div>
  </wd-action-sheet>
</template>

<style scoped lang="scss">
.order-search-container{
  min-height: calc(100vh - 120px);
}
.tabs-fillet-corner {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  position: relative;
  box-sizing: border-box;
  overflow: hidden;
  background: #F1F4FF;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}
.tabs-fillet-corner-item-wrap {
  flex: 1;
  height: 46px;
  padding: 0 12px;
}
.tabs-fillet-corner-item-wrap:first-child .tabs-fillet-corner-item {
  border-top-left-radius: 0;
}
.tabs-fillet-corner-item-wrap:first-child
.tabs-fillet-corner-item-active::before {
  border-radius: 0;
  transform: skew(0deg);
  left: -17px;
}
.tabs-fillet-corner-item-wrap:last-child .tabs-fillet-corner-item {
  border-top-right-radius: 0;
}

.tabs-fillet-corner-item-wrap:last-child
.tabs-fillet-corner-item-active::after {
  border-radius: 0;
  transform: skew(0deg);
  right: -17px;
}

.tabs-fillet-corner-item {
  border-radius: 8px 8px 0 0;
  width: 100%;
  height: 100%;
  position: relative;
  background: #F1F4FF; // ✅ 加上这行
}
.tabs-fillet-corner-item::before,
.tabs-fillet-corner-item::after {
  content: '';
  position: absolute;
  top: 0;
  width: 12px;
  height: 100%;
  z-index: 9;
  background: #F1F4FF;
}
.tabs-fillet-corner-item::before {
  border-bottom-left-radius: 6px;
  transform: skew(17deg);
  left: -18px;
}
.tabs-fillet-corner-item::after {
  border-bottom-right-radius: 6px;
  transform: skew(-17deg);
  right: -18px;
}
.tabs-fillet-corner-item-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin: 0 auto;
  font-size: 30rpx;
  line-height: 30px;
  color: #666666;
  text-align: center;
  position: relative;
  cursor: pointer;
  z-index: 99;
}
.tabs-fillet-corner-item-active {
  background: #FFFFFF; // ✅ 修改这里
  z-index: 2;
  padding-top: 5px;
}
.tabs-fillet-corner-item-active .tabs-fillet-corner-item-text {
  font-weight: 500;
  color: #333333;
}
.tabs-fillet-corner-item-active::before,
.tabs-fillet-corner-item-active::after {
  content: '';
  position: absolute;
  top: 0;
  width: 17px;
  height: 100%;
  background: #FFFFFF;
  border-radius: 17px 17px 0 0;
}
.tabs-fillet-corner-item-active::before {
  transform: skew(-17deg);
  left: -6.5px;
  box-shadow: -5px 15px 0 #FFFFFF;
}
.tabs-fillet-corner-item-active::after {
  transform: skew(17deg);
  right: -6.5px;
  box-shadow: 5px 15px 0 0 #FFFFFF;
}

.tabs-fillet-corner-item-icon{
  font-size: 40px;
  color: #2540F3;
}

.payment-container{
  box-shadow: 0rpx 2rpx 12rpx 0rpx rgba(0,0,0,0.1);
}
:deep(.wd-upload__evoke-slot){
  width: 100%;
}
.upload-box{
  background-image: url(@/static/svg/upload-cover.svg);
  background-size: 100% 100%;
  background-position: center;
}
.upload-icon{
  box-shadow: -3rpx 3rpx 12rpx 0rpx #8894C8;
}
.input-container{
  :deep(.wd-cell){
    padding-left: 0 !important;
    .wd-cell__wrapper.is-vertical .wd-cell__right{
      margin-top: 5px !important;
    }
  }
}
.upload-container{
  :deep(.wd-upload__preview){
    width: 100% !important;
    height: 230px !important;
  }
}
</style>

<style>
.custom-action-sheet{
  min-height: 100%;
  background-image: url('https://img.picui.cn/free/2025/05/02/6814cfc76751a.png') !important;
  background-size: cover;
  background-position: center;
}

.custom-action-sheet__header{
  font-size: 18px !important;
  font-weight: bold !important;
  line-height: 3 !important;
  height: auto !important;
}
</style>
